import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import Request from '@/apis/request'

export const useUserStore = defineStore('User', () => {
  const token = ref(null) // 记录token
  const loaded = ref(false) // 保存一个标识信息，指示登陆后需要加载的初始化数据是否完成
  const user = ref(null) // 保存当前用户
  // 获取token
  const getToken = () => token.value || localStorage.getItem('token')
  // 是否已加载
  const isLoaded = () => loaded.value
  // 获取当前用户
  const getUser = () => user.value
  // 加载用户
  const loadUser = async () => {
    // 发送获取当前用户信息请求
    const data = await Request.requestJson(Request.GET, '/user/info', null)
    user.value = data.data
  }
  // 设置是否加载完成
  const setLoaded = (isLoaded) => {
    loaded.value = isLoaded
  }
  // 重置数据
  const resetSaveData = () => {
    loaded.value = false
    user.value = null
    token.value = null
    localStorage.removeItem('token')
  }
  // 设置token
  const setToken = (JWT) => {
    token.value = JWT
    localStorage.setItem('token', JWT)
  }
  return {
    getToken,
    isLoaded,
    getUser,
    loadUser,
    setLoaded,
    setToken,
    resetSaveData
  }
})
